package com.example.caoben_back.contoller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.caoben_back.entity.po.Post;
import com.example.caoben_back.entity.po.PostParams;
import com.example.caoben_back.entity.po.User;
import com.example.caoben_back.entity.vo.Result;
import com.example.caoben_back.service.IPostService;
import com.example.caoben_back.service.impl.PostCacheService;
import com.example.caoben_back.utils.TokenUtil;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/post")
public class PostController {

    @Autowired
    private IPostService postService;
    
    @Autowired
    private PostCacheService postCacheService;


    // 发布帖子
    @PostMapping("/publish")
    public Result<Integer> publishPost(@RequestBody PostParams params,
                                       HttpServletRequest request) {
        // 从token中解析用户信息
        User user = TokenUtil.getUserFromRequest(request);
        if (user == null) {
            return Result.fail("用户未登录");
        }
        Integer userId = user.getUserId();
        
        Post post = new Post();
        post.setUserId(userId);
        post.setTitle(params.getTitle());
        post.setContent(params.getContent());
        post.setPublishTime(LocalDateTime.now());
        post.setImageCount(params.getImageUrls() != null ? params.getImageUrls().size() : 0);
        postService.save(post);
        
        // 清除相关缓存
        postCacheService.updateHotPostListCache();
        
        // 若有图片，同步保存到image表（此处省略）
        return Result.success(post.getPostId());
    }

    // 获取帖子列表（分页）
    @GetMapping("/list")
    public Result<Map<String, Object>> getPostList(@RequestParam Integer page, 
                                                 @RequestParam Integer size) {
        // 使用缓存获取热门帖子列表
        // Page<Post> postPage = postService.page(new Page<>(page, size),
        //         new QueryWrapper<Post>().orderByDesc("publish_time"));
        
        // 改为使用缓存服务获取热门帖子
        java.util.List<Post> posts = postCacheService.getHotPostList(page, size);
        long total = postService.count(); // 简化处理总数
        
        Map<String, Object> data = new HashMap<>();
        data.put("list", posts);
        data.put("total", total);
        return Result.success(data);
    }

    // 获取帖子详情
    @GetMapping("/detail")
    public Result<Post> getPostDetail(@RequestParam Integer postId) {
        // Post post = postService.getById(postId);
        // 改为使用缓存服务获取帖子详情
        Post post = postCacheService.getPostDetail(postId);
        return Result.success(post);
    }

    // 获取用户发布的帖子
    @GetMapping("/user")
    public Result<Map<String, Object>> getUserPosts(@RequestParam Integer userId,
                                                  @RequestParam Integer page,
                                                  @RequestParam Integer size) {
        Page<Post> postPage = postService.page(new Page<>(page, size),
                new QueryWrapper<Post>().eq("user_id", userId).orderByDesc("publish_time"));
        Map<String, Object> data = new HashMap<>();
        data.put("list", postPage.getRecords());
        data.put("total", postPage.getTotal());
        return Result.success(data);
    }

    // 删除帖子 - 用户可以删除自己的帖子，管理员可以删除任何帖子
    @DeleteMapping("/delete")
    public Result<Boolean> deletePost(@RequestParam Integer postId, 
                                     HttpServletRequest request) {
        // 从token中解析用户信息
        User currentUser = TokenUtil.getUserFromRequest(request);
        if (currentUser == null) {
            return Result.fail("用户未登录");
        }
        
        // 获取要删除的帖子
        Post post = postService.getById(postId);
        if (post == null) {
            return Result.fail("帖子不存在");
        }
        
        // 检查权限：用户可以删除自己的帖子 或 管理员可以删除任何帖子
        if (!post.getUserId().equals(currentUser.getUserId()) && 
            (currentUser.getIfAmdin() == null || currentUser.getIfAmdin() != 1)) {
            return Result.fail("没有权限删除该帖子");
        }
        
        // 执行删除操作
        boolean result = postService.removeById(postId);
        
        // 清除相关缓存
        if (result) {
            postCacheService.clearPostCache(postId);
            postCacheService.updateHotPostListCache();
        }
        
        return Result.success(result);
    }
}